<template>
  <div>
    <!-- 第一行 返回按钮 -->
    <div class="back">
      <!-- $router.go(-1) 表示返回上一个路由页面 -->
      <el-page-header content="发布页面" @back="$router.go(-1)" />
    </div>
    <!-- 第二行 表单 -->
    <div class="form" style="margin-top: 10px;">
      <el-form ref="myForm" :model="form" :rules="rules">
        <el-row>
          <el-col :span="16">
            <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="分类" :label-width="formLabelWidth" prop="categoryId">
              <el-select v-model="form.categoryId" clearable placeholder="请选择文章分类栏目">
                <el-option
                  v-for="item in categories"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="封面" :label-width="formLabelWidth" prop="cover">
              <el-upload
                class="avatar-uploader"
                action="http://121.4.83.32:7006/UploadControlle/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 富文本编辑器 Tinymce -->
        <el-form-item label="正文" :label-width="formLabelWidth" prop="content">
          <Tinymce v-model="form.content" :height="300" placeholder="请输入文章内容" />
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" style="float: right;" @click="toSave">发布文章</el-button>
  </div>
</template>
<script>
import { get, post } from '@/utils/request'
import { mapGetters } from 'vuex'
// 引入富文本编辑器组件
import Tinymce from '@/components/Tinymce'
export default {
  // 局部注册组件
  components: {
    'Tinymce': Tinymce
  },
  computed: {
    ...mapGetters(['userData'])
  },
  data() {
    return {
      // 所有文章
      articleData: [],
      params: {
        page: 1,
        pageSize: 5
      },
      // 文章数量
      total: 0,
      // 表单对象
      form: {},
      // 表单域标签宽度
      formLabelWidth: '60px',
      categories: [''],
      imageUrl: '',
      // 发布文章校验规则
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择文章分类栏目', trigger: 'change' }
        ],
        cover: [
          { required: true, message: '请上传封面图片', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCategory()
    this.form = { ...this.$route.query }
    this.form.authorId = this.userData.id
    this.imageUrl = this.form.cover
  },
  methods: {
    // 分页多条件查询所有文章信息
    async getArticle() {
      // 分页 page pageSize 多条件 title status categoryId
      const temp = {
        ...this.params,
        ...this.form
      }
      // 判断条件是否存在 不存在删除条件
      for (const key in temp) {
        if (!temp[key]) {
          delete temp[key]
        }
      }
      const res = await get('/article/pageQuery', temp)
      console.log(res, '获取响应')
      this.articleData = res.data.list
      this.total = res.data.total
    },
    // 保存文章
    toSave() {
      // 对表单进行校验
      this.$refs['myForm'].validate(async(valid) => {
        if (valid) {
          // 校验通过--->发起一个保存请求
          const res = await post('/article/saveOrUpdate', this.form)
          if (res.status == 200) {
            this.$message({
              title: '发布文章',
              type: 'success',
              message: res.message
            })
            // 跳转到文章列表页面
            this.$router.push('/admin/info/article/List')
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
          // 重新载入数据
          // this.getArticle();
        } else {
          // 校验不通过--->return false
          return false
        }
      })
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(res);
      // 将图片地址设置给表单对象封面属性
      this.form.cover = res.data
      this.rules.cover = ''
    },
    // 图片上传之前触发的函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async getCategory() {
      const res = await get('/category/findAll')
      // console.log(res,'获取响应');
      this.categories = res.data
    }
  }
}
</script>
